package zmee.src.formplugin;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.TempFileCache;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.fileservice.BatchDownloadRequest;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.logging.BizLog;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.orm.util.StringUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.scm.pds.common.attach.AttachmentUtils;
import kd.scm.pds.common.bridge.MultiLangEnumBridge;
import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SrcBatchDownloadDocMarkTwoEdit extends AbstractBillPlugIn {
    private static String OPKEY_BACHDOWLOAD = "bachdowload";

    public SrcBatchDownloadDocMarkTwoEdit() {
    }

    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        String opkey = ((AbstractOperate)args.getSource()).getOperateKey();
        if (opkey.equals(OPKEY_BACHDOWLOAD)) {
            DynamicObject dataEntity = this.getView().getModel().getDataEntity(true);
            DynamicObjectCollection selectEntryColls = this.getSelectEntryColls();
            String billNo = "";
            List<BatchDownloadRequest.Dir> dirList = new ArrayList(selectEntryColls.size());
            DynamicObject obj = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), "src_project");
            if (obj == null) {
                return;
            }

            billNo = obj.getString("billno");

            String filterName;
            for(int index = 0; index < selectEntryColls.size(); ++index) {
                DynamicObject entry = (DynamicObject)selectEntryColls.get(index);
                DynamicObjectCollection bidattachCols = entry.getDynamicObjectCollection("bidattach");
                DynamicObject supplier = entry.getDynamicObject("supplier");
                DynamicObject packageObj = entry.getDynamicObject("package");
                String packageName = "";
                if (packageObj != null) {
                    packageName = packageObj.getString("packagename");
                }

                String supplierName = "";
                if (this.getModel().getDataEntity().getBoolean("projectf7.ishidesupplier")) {
                    supplierName = entry.getString("suppliercode");
                } else if (supplier != null) {
                    supplierName = supplier.getString("name");
                }

                String packfiletype = entry.getString("packfiletype");
                if (bidattachCols != null && bidattachCols.size() > 0) {
                    List<BatchDownloadRequest.File> fileList = new ArrayList(bidattachCols.size());
                    supplierName = StringUtils.isEmpty(supplierName) ? "" : supplierName + "-";
                    packageName = StringUtils.isEmpty(packageName) ? "" : "-" + packageName;
                    filterName = "(" + (index + 1) + ")" + supplierName + ThisPackFileTypeEnums.getName(packfiletype) + packageName;
                    BatchDownloadRequest.Dir testDir = new BatchDownloadRequest.Dir(filterName);
                    Iterator var19 = bidattachCols.iterator();

                    while(var19.hasNext()) {
                        DynamicObject bidattachCol = (DynamicObject)var19.next();
                        DynamicObject attachInfo = bidattachCol.getDynamicObject("fbasedataid");
                        String url = attachInfo.getString("url");
                        String name = getName(packfiletype, attachInfo);
                        String path = url;
                        if (url.contains("configKey=redis.serversForCache&id=tempfile")) {
                            path = AttachmentUtils.uploadTempFile(url, name);
                        }

                        if (url.contains("path=")) {
                            path = kd.bos.dataentity.utils.StringUtils.substringAfter(url, "path=");
                        }

                        try {
                            path = URLDecoder.decode(path, "UTF-8");
                        } catch (UnsupportedEncodingException var26) {
                            BizLog.log(String.format("URLdecode error:%s;path:%s", var26.getMessage(), url));
                        }

                        BizLog.log("###SrcBatchDownloadDocEdit batchdown path:" + url);
                        BatchDownloadRequest.File aFile = new BatchDownloadRequest.File(name, path);
                        fileList.add(aFile);
                    }

                    testDir.setFiles((BatchDownloadRequest.File[])fileList.toArray(new BatchDownloadRequest.File[0]));
                    dirList.add(testDir);
                }
            }

            if (CollectionUtils.isEmpty(dirList)) {
                return;
            }

            long timeMillis = System.currentTimeMillis();
            String fileName = String.format(ResManager.loadKDString("%1$s_全部附件_%2$s.zip", "SrcBatchDownloadDocEdit_0", "scm-src-formplugin", new Object[0]), billNo, timeMillis);
            BatchDownloadRequest bdr = new BatchDownloadRequest(fileName);
            bdr.setDirs((BatchDownloadRequest.Dir[])dirList.toArray(new BatchDownloadRequest.Dir[0]));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            FileService fs = FileServiceFactory.getAttachmentFileService();
            fs.batchDownload(bdr, out, RequestContext.getOrCreate().getUserAgent());
            ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
            TempFileCache e = CacheFactory.getCommonCacheFactory().getTempFileCache();
            int timeout = 7200;
            filterName = e.saveAsUrl(fileName, in, timeout);
            this.getView().download(filterName);
        }

    }

    @NotNull
    private String getName(String packfiletype, DynamicObject attachInfo) {
        String rawName = attachInfo.getString("name");
        int index = rawName.indexOf(".");
        return ThisPackFileTypeEnums.getName(packfiletype) + rawName.substring(index);
    }

    private DynamicObjectCollection getSelectEntryColls() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        IFormView view = this.getView();
        EntryGrid entryGrid = (EntryGrid)view.getControl("entryentity");
        int[] selectRows = entryGrid.getSelectRows();
        DynamicObjectCollection entryCols = null;
        if (selectRows.length == 0) {
            entryCols = dataEntity.getDynamicObjectCollection("entryentity");
        } else {
            entryCols = new DynamicObjectCollection();
            int[] var6 = selectRows;
            int var7 = selectRows.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                int index = var6[var8];
                DynamicObjectCollection entryentity = this.getModel().getDataEntity(true).getDynamicObjectCollection("entryentity");
                DynamicObject entryData = (DynamicObject)entryentity.get(index);
                entryCols.add(entryData);
            }
        }

        return entryCols;
    }
}

enum ThisPackFileTypeEnums{
    OTH(new MultiLangEnumBridge("资信标书", "PackFileTypeEnums_3", "scm-pds-common"), "1"),
    TEC(new MultiLangEnumBridge("技术标书", "PackFileTypeEnums_0", "scm-pds-common"), "2"),
    BIZ(new MultiLangEnumBridge("商务标书", "PackFileTypeEnums_1", "scm-pds-common"), "3");

    private MultiLangEnumBridge bridge;
    private String value;

    private ThisPackFileTypeEnums(MultiLangEnumBridge bridge, String value) {
        this.bridge = bridge;
        this.value = value;
    }

    public String getName() {
        return this.bridge.loadKDString();
    }

    public String getValue() {
        return this.value;
    }

    public static String getName(String value) {
        ThisPackFileTypeEnums[] var1 = values();
        int var2 = var1.length;

        for(int var3 = 0; var3 < var2; ++var3) {
            ThisPackFileTypeEnums type = var1[var3];
            if (type.getValue().equals(value)) {
                return type.getName();
            }
        }
        return "标书附件";
    }
}
